import { defineStore } from 'pinia'
import { getToken, setToken, removeToken } from '@/utils/token'

export const useUserStore = defineStore('user', {
  state: () => ({
    id: null,
    account: '',
    name: '',
    avatar: '',
    token: null,
    role: '', // 添加角色字段
  }),

  getters: {
    // 是否登录的状态判断
    isLoggedIn: (state) => !!state.token,
    // 获取用户角色
    getUserRole: (state) => state.role,
    // 检查是否为管理员
    isAdmin: (state) => state.role === 'admin',
    // 检查是否为普通用户
    isUser: (state) => state.role === 'user',
  },

  actions: {
    // 保存用户信息
    setUserInfo(info) {
      this.$patch(info)

      // 保存令牌到localStorage
      if (info.token) {
        setToken(info.token)
      }

      // 将用户信息保存到本地存储，实现刷新页面后仍能保持登录状态
      localStorage.setItem(
        'userInfo',
        JSON.stringify({
          id: this.id,
          account: this.account,
          name: this.name,
          avatar: this.avatar,
          role: this.role,
        }),
      )
    },

    // 清除用户信息（退出登录）
    clearUserInfo() {
      this.$reset()
      localStorage.removeItem('userInfo')
      removeToken()
    },

    // 从本地存储加载用户信息
    loadUserInfo() {
      // 优先从localStorage获取令牌
      const token = getToken()
      if (token) {
        this.token = token
      }

      const info = localStorage.getItem('userInfo')
      if (info) {
        this.setUserInfo(JSON.parse(info))
      }
    },

    // 设置用户角色
    setUserRole(role) {
      this.role = role
      // 同步更新本地存储
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        const parsedInfo = JSON.parse(userInfo)
        parsedInfo.role = role
        localStorage.setItem('userInfo', JSON.stringify(parsedInfo))
      }
    },

    // 检查是否有指定角色
    hasRole(role) {
      if (typeof role === 'string') {
        return this.role === role
      }

      if (Array.isArray(role)) {
        return role.includes(this.role)
      }

      return false
    }
  },
})
